const _process = require("node:process");
const {
    stdout_columns,
    clear_line_end,
    shareData,
} = require("../commands/share_data");
const { clearLine } = require("./interaction_tool");
const { omit, omit_offset, write } = require("./log_tool");
const {
    alignNumber,
    formatByteSize,
    alignStr,
    Alignment,
    formatTimeInMillisec,
} = require("./transform_tool");
require("colors");

const color_cfg = ["cyan", "green", "white"];

/**
 *
 * @param {*} cur
 * @param {*} total
 * @param {{
 *  char_count?: number,
 *  char1?: string,
 *  char2?: string,
 *  desc?: string,
 *  show_progress_txt?: boolean,
 *  color?: string = "reset",
 *  depth?: number = 0,
 *  align?: boolean = false,
 * }} options
 */
function progress(cur, total, options, important) {
    if (shareData.FULL_AUTOMATIC && !important) {
        write(".");
        return;
    }
    let depth = options?.depth || 0;
    depth = Math.min(depth, 5);
    const color =
        options.color || color_cfg[Math.min(color_cfg.length - 1, depth)];
    const padding = 4;
    options = Object.assign(
        {},
        {
            char_count: 30,
            char1: "━"[color],
            char2: "━".gray,
            desc: "",
            show_progress_txt: true,
        },
        options,
    );
    // options.color = "gray";
    let {
        char_count,
        char1,
        char2,
        desc,
        show_progress_txt,
        format_bytes,
        format_time,
    } = options;
    char_count -= depth * padding;
    if (char_count <= 0) char_count = 10;
    percent =
        cur >= total ? 100 : alignNumber(Math.floor((100 * cur) / total), 100);
    char_num =
        cur >= total ? char_count : Math.floor((char_count * cur) / total);
    if (format_time) {
        cur = formatTimeInMillisec(cur, "hh:mm:ss");
        total = formatTimeInMillisec(total, "hh:mm:ss");
        curr_total = `(${alignNumber(cur, total)}/${total})`;
    } else if (format_bytes) {
        cur = formatByteSize(cur);
        total = formatByteSize(total);
        curr_total = `(${alignNumber(cur, total)}/${total})`;
    } else {
        curr_total = `(${alignNumber(cur, total > 0 ? total : cur)}/${total > 0 ? total : "∞"})`;
    }
    chars1 = char1.repeat(char_num);
    chars2 = char2.repeat(char_count - char_num);

    let progressChars;
    if (show_progress_txt)
        progressChars = `${chars1}${chars2} ${percent}% ${curr_total} ${desc}`;
    else progressChars = `${chars1}${chars2} ${desc}`;
    if (!shareData.FULL_AUTOMATIC) {
        progressChars = `\r${progressChars[color]}${clear_line_end}`;
    } else {
        progressChars = `${progressChars}\n`;
    }
    if (options.align) {
        // progressChars = `${alignStr(progressChars, stdout_columns, {alignment: Alignment.LEFT})}`;
    } else {
        //     // 清空本行
        // clearLine();
        //     write(`${progressChars}`)
    }
    write(progressChars);
}

module.exports = {
    progress,
};
